import fly from '../utils/request.js';
import store from "../store";
import {
	wxAuth,
	register
} from './user.js';
import utils from '@/utils/util'
//异步封装登录
async function toLogin() {
	return await new Promise((resolve, reject) => {
		uni.login({
			success(res) {
				if (res.code) {
					resolve(res.code)
				}
			}
		})
	})
}
//登录
export const login = async (params = {}) => {
	//登陆后是否需要刷新当前页面,在调用login方法时传进来
	var refresh_page = params.refresh_page;
	delete params['refresh_page'];
	let code = await toLogin()
	//你们的获取openid接口
	let res = await fly.get('/login/wxAuth', {
		code: code,
		user_pass: true,
		not_loading: true,
		...params
	})
	uni.setStorageSync('session_key', res.data.session_key)
	uni.setStorageSync('openid', res.data.openid)
	//不是第一次登录,直接获取用户信息
	if (uni.getStorageSync('isCanUse')) {
		console.log("11111111")
		uni.getUserInfo({
			provider: 'weixin',
			success: function(infoRes) {

				let data = {
					...infoRes.userInfo,
					openid: uni.getStorageSync('openid'),
					user_pass: true,
					unionid: "12121212sfasf"
				};
				// 后台换取token
				register(data).then((res) => {
					//存入vuex需要的数据
					this.$store.commit('setUser', data);
					this.$store.commit('setToken', data.token);
				});
			},
			fail(res) {}
		});
	}
}
